﻿using System.Linq;
using BoldBrick.Core.Logging;
using BoldBrick.OneIntranet.HR.DataObjects;
using BoldBrick.OneIntranet.HR.DataObjects.ContentTypes;
using BoldBrick.OneIntranet.HR.DataObjects.Lists;
using BoldBrick.OneIntranet.HR.Resources;
using BoldBrick.OneIntranet.HR.Workflows;
using Microsoft.SharePoint;
using BoldBrick.SharePoint.CommonControls.Extensions;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace BoldBrick.OneIntranet.HR.EventHandlers
{
	public class CandidatesListItemAdded : SPItemEventReceiver
	{
		private static readonly ILogger log = Logger.GetLogger(typeof(CandidatesListItemAdded));

		public override void ItemAdded(SPItemEventProperties properties)
		{
			base.ItemAdded(properties);

			SPListItem listItem = properties.ListItem;
			log.Write(LogLevel.Info, "ItemAdded for '{0}' item started.", listItem.Url);
			//SPFolder folder = listItem.Folder;
			if (properties.ListItem.Folder == null)
			{
				// setup Title as content type name
				if (string.IsNullOrEmpty(listItem.Title))
				{
					listItem[SharePoint.CommonControls.DataObjects.SiteColumns.TitleColumn.InternalName] =
						listItem[SharePoint.CommonControls.DataObjects.SiteColumns.ContentTypeColumn.InternalName];
					listItem.Update(false);
				}
				
				ItemAddedHandler(properties);
			}
			else
			{
				SetupFolder(properties);
			}
		}

		#region ------ Item Added Handlers --------------------------------------------------------

		/// <summary>
		/// Handler for item added
		/// </summary>
		/// <param name="properties">Properties of the event</param>
		private static void ItemAddedHandler(SPItemEventProperties properties)
		{
			// get Canidate item
			SPListItem listItem = properties.ListItem;

			// choose handler according to item content type
			if (listItem.ContentTypeId.IsChildOf(ContentTypes.FinalDecisionResultContentType.ID))
			{
				ItemAddedHandler_FinalDecisionResult(properties);
			}
			else if (listItem.ContentTypeId.IsChildOf(ContentTypes.CandidateDecisionResultContentType.ID))
			{
				ItemAddedHandler_CandidateDecisionResult(properties);
			}
		}

		/// <summary>
		/// Handler for Final decision result item
		/// </summary>
		/// <param name="properties">Properties of the event</param>
		private static void ItemAddedHandler_FinalDecisionResult(SPItemEventProperties properties)
		{
			// get candidate's item
			SPListItem listItem = properties.ListItem;
			string folderUrl = SPUtility.GetUrlDirectory(listItem.Url);
			SPFolder folderCandidate = properties.Web.GetFolder(folderUrl);
			if (folderCandidate == null)
				return;

			SPListItem itemCandidate = folderCandidate.Item;

			// set result
			itemCandidate[SiteColumns.CandidateResultColumn.InternalName] =
				listItem[SiteColumns.CandidateResultColumn.InternalName];
			itemCandidate.Update();

			// cancel workflow
			HRWorkflowHelper.CancelWorkflowElevated(properties.SiteId, properties.Web.ID,
				properties.ListId, itemCandidate.ID, Lists.CandidatesList.HrWorkflow.ID);
		}

		/// <summary>
		/// Handler for Candidate decision result item
		/// </summary>
		/// <param name="properties">Properties of the event</param>
		private static void ItemAddedHandler_CandidateDecisionResult(SPItemEventProperties properties)
		{
			// get Canidate item
			SPListItem listItem = properties.ListItem;

			string folderUrl = SPUtility.GetUrlDirectory(listItem.Url);
			SPFolder folderCandidate = properties.Web.GetFolder(folderUrl);
			if (folderCandidate == null)
				return;
			
			// if canidate won't to be hired
			string noHireValue = ResourceBuilder.GetResource("Field_CandidateResult_Value_NoHire", properties.Web.Language);
			string result = listItem.GetValueObject<string>(SiteColumns.CandidateResultColumn.InternalName);
			if (result != noHireValue)
				return;

			SPListItem itemCandidate = folderCandidate.Item;
			// update Candidate's item 
			itemCandidate[SiteColumns.CandidateResultColumn.InternalName] = noHireValue;
			itemCandidate.Update();

			// cancel workflow
			HRWorkflowHelper.CancelWorkflowElevated(properties.SiteId, properties.Web.ID, 
				properties.ListId, properties.ListItemId, Lists.CandidatesList.HrWorkflow.ID);
			
		}

		#endregion

		#region ------ Setup Folder ---------------------------------------------------------------

		/// <summary>
		/// Setups candidate' sfolder
		/// </summary>
		/// <param name="properties">Properties of the event</param>
		private static void SetupFolder(SPItemEventProperties properties)
		{
			SPSecurity.RunWithElevatedPrivileges(delegate
			{
				using (SPSite site = new SPSite(properties.SiteId))
				{
					using (SPWeb web = site.OpenWeb(properties.Web.ID))
					{
						SPList list = web.Lists[properties.ListId];
						SPListItem listItem = list.GetItemById(properties.ListItemId);
						SPFolder folder = listItem.Folder;

						// setup content types
						Lists.CandidatesList.SetupContentTypeUniqueOrder(list, folder);

						// rename folder to better name <LastName FirstName (ID)>
						string title = string.Format("{0} {1} ({2})",
							listItem[SiteColumns.LastNameColumn.InternalName],
							listItem[SiteColumns.FirstNameColumn.InternalName],
							listItem.ID);

						listItem[SharePoint.CommonControls.DataObjects.SiteColumns.NameColumn.InternalName] = title;
						listItem.SystemUpdateWithNoEvents();
					}
				}

			});

		}

		#endregion
	}
}
